#! /usr/bin/env python3
# encoding: utf-8
"""
@file: views.py
@author: www.xcooo.cn
@Mail: 602006050@qq.com
"""
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import redis_store
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu

@index_blu.route('/news_list')
def news_list():
    """
    获取首页新闻数据
    :return:
    """
    # 1.获取参数
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')

    # 2.校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 加载首页数据时,status = 0 才能显示
    filters = [News.status == 0]
    if cid != 1: # 查询的不是最新的数据
        # 需要添加条件
        filters.append(News.category_id == cid)

    # 3.查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')

    # 取出当前页数据
    news_object_list = paginate.items # 模型对象列表
    total_page = paginate.pages
    current_page = paginate.page

    # 将模型对象列表转换成字典列表
    news_dict = []
    for news in news_object_list:
        news_dict.append(news.to_basic_dict())

    data = {
        'news_dict':news_dict,
        'total_page':total_page,
        'current_page':current_page
    }

    return jsonify(errno=RET.OK, errmsg='ok',data = data)

@index_blu.route('/')
@user_login_data
def index():
    """
    首页逻辑实现
    如果用户已登陆,将用户参数传递到模板中显示
    :return:
    """
    # 显示用户登陆的逻辑
    # 获取用户id
    # user_id = session.get('user_id',None)
    # user = None
    # # 查找用户id对应的用户模型
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user

    # 显示右侧新闻排行的逻辑
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 定义一个空的字典列表
    news_dict = []
    # 遍历对象列表,将对象的字典添加到字典列表中
    for news in news_list:
        news_dict.append(news.to_basic_dict())

    # 查询分类数据(查询出来为模型对象),通过模板渲染
    categories = Category.query.all()

    # 将模型对象列表转换成字典列表
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    data = {
        'user':user.to_dict() if user else None,
        'news_dict':news_dict,
        'category_list':category_list
    }
    return render_template('news/index.html',data=data)

# 打开网站，默认请求favicon.ico的小图标
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')



